﻿using Consul;
using Microsoft.Extensions.Configuration;

namespace ServiceManagement.Consul
{
    /// <summary>
    /// 服务注册和发现
    /// </summary>
    public static class ConsulHelper
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="configuration">配置</param>
        public static void Register(this IConfiguration configuration)
        {
            //访问consul的配置
            ConsulClient client = new ConsulClient(c =>
            {
                //consul地址
                c.Address = new Uri(configuration["Consul:Address"]);
                //consul名称
                c.Datacenter = configuration["Consul:Datacenter"];
            });
            //注册心跳检测
            AgentServiceRegistration registration = new AgentServiceRegistration();
            //唯一标识
            registration.ID = Guid.NewGuid().ToString();
            //API服务名称
            registration.Name = configuration["Consul:ServiceName"];
            //API服务地址
            registration.Address = configuration["Consul:ServiceAddress"];
            //API的服务端口号
            registration.Port = int.Parse(configuration["Consul:ServicePort"]);

            //健康检查
            registration.Check = new AgentServiceCheck()
            { 
                //健康检查地址
                HTTP = $"http://{registration.Address}:{registration.Port}/api/HealthCheck",
                //间隔时间
                Interval = TimeSpan.FromSeconds(10),
                //超时时间
                Timeout = TimeSpan.FromSeconds(5),
                //移除时间
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
            };
            client.Agent.ServiceRegister(registration);
        }
    }
}
